<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务编码" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in pm_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option
            v-for="dict in pm_task_priority"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          v-hasPermi="['pm:task:add']"
        >
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:task:edit']"
        >
          <el-icon><Edit /></el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:task:remove']"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务编码" align="center" prop="taskCode" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag 
            :options="pm_task_status || []" 
            :value="scope.row.status"
            v-if="pm_task_status && pm_task_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template #default="scope">
          <dict-tag 
            :options="pm_task_priority || []" 
            :value="scope.row.priority"
            v-if="pm_task_priority && pm_task_priority.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.priority || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" prop="progress">
        <template #default="scope">
          <el-progress :percentage="Number(scope.row.progress) || 0" :stroke-width="8"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="assigneeName" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.startDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:task:query']"
          >
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:task:edit']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:task:remove']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="isView ? {} : rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="isView" />
        </el-form-item>
        <el-form-item label="任务编码" prop="taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务编码" :disabled="isView" />
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" clearable :disabled="isView" @change="handleProjectChange">
            <el-option
              v-for="project in projectList"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入任务描述" :disabled="isView" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="form.taskType" placeholder="请选择任务类型" :disabled="isView">
            <el-option
              v-for="dict in pm_task_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择任务状态" :disabled="isView">
            <el-option
              v-for="dict in pm_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" :disabled="isView">
            <el-option
              v-for="dict in pm_task_priority"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预估工时" prop="estimatedHours">
          <el-input v-model="form.estimatedHours" placeholder="请输入预估工时" :disabled="isView" />
        </el-form-item>
        <el-form-item label="负责人" prop="assigneeId">
          <el-select v-model="form.assigneeId" placeholder="请选择负责人" clearable :disabled="isView">
            <el-option
              v-for="user in projectMemberList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
          <div class="el-form-item__help" style="color: #909399; font-size: 12px; margin-top: 4px;">
            建议选择项目成员作为任务负责人
          </div>
        </el-form-item>
        <el-form-item label="报告人" prop="reporterId">
          <el-select v-model="form.reporterId" placeholder="请选择报告人" clearable :disabled="isView">
            <el-option
              v-for="user in projectMemberList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
          <div class="el-form-item__help" style="color: #909399; font-size: 12px; margin-top: 4px;">
            建议选择项目成员作为任务报告人
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue'
import type { FormInstance } from 'element-plus'
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/pm/task";
import { listProject } from "@/api/pm/project";
import { listUser } from "@/api/system/user";
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue';

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据 - 使用 proxy.useDict 方式
const { pm_task_status, pm_task_priority, pm_task_type } = toRefs<any>(proxy?.useDict('pm_task_status', 'pm_task_priority', 'pm_task_type'))

// 表单引用
const formRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()

// 响应式数据
const loading = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const taskList = ref<any[]>([])
const projectList = ref<any[]>([])
const userList = ref<any[]>([])
const projectMemberList = ref<any[]>([]) // 项目成员列表
const title = ref("")
const open = ref(false)
const isView = ref(false) // 是否为查看模式

// 查询参数
const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  projectId: null,
  taskName: null,
  taskCode: null,
  status: null,
  priority: null,
  assigneeId: null,
  parentId: null,
})

// 表单参数
const form = ref<any>({
  taskId: null,
  projectId: null,
  parentId: null,
  taskName: null,
  taskCode: null,
  description: null,
  taskType: "development",
  status: "todo",
  priority: "medium",
  progress: 0,
  startDate: null,
  endDate: null,
  actualStartDate: null,
  actualEndDate: null,
  estimatedHours: null,
  actualHours: null,
  assigneeId: null,
  reporterId: null,
  sortOrder: 0,
  remark: null
})

// 表单校验
const rules = reactive({
  taskName: [
    { required: true, message: "任务名称不能为空", trigger: "blur" }
  ],
  taskCode: [
    { required: true, message: "任务编码不能为空", trigger: "blur" }
  ],
  projectId: [
    { required: true, message: "项目不能为空", trigger: "change" }
  ],
  status: [
    { required: true, message: "任务状态不能为空", trigger: "change" }
  ],
  priority: [
    { required: true, message: "优先级不能为空", trigger: "change" }
  ]
})

// 生命周期
onMounted(() => {
  getList()
  getProjectList()
  getUserList()
})

// 方法定义
/** 查询任务管理列表 */
const getList = () => {
  loading.value = true;
  listTask(queryParams).then(response => {
    taskList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取任务列表失败:', error);
    taskList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 查询项目列表 */
const getProjectList = () => {
  listProject().then(response => {
    projectList.value = response.rows || [];
  }).catch(error => {
    console.error('获取项目列表失败:', error);
    projectList.value = [];
  });
}

/** 查询用户列表 */
const getUserList = () => {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userList.value = response.rows || [];
    // 初始化时，项目成员列表包含所有用户
    projectMemberList.value = response.rows || [];
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    userList.value = [];
    projectMemberList.value = [];
  });
}

/** 查询项目成员列表（用于任务分配） */
const getProjectMemberList = (projectId) => {
  if (!projectId) {
    projectMemberList.value = userList.value; // 如果没有项目ID，显示所有用户
    return;
  }
  
  // 调用项目成员API获取当前项目的成员列表
  import('@/api/pm/project').then(({ getProjectMembers }) => {
    getProjectMembers(projectId).then(response => {
      if (response.data && response.data.length > 0) {
        // 将项目成员转换为用户格式
        projectMemberList.value = response.data.map(member => ({
          userId: member.userId,
          userName: member.userName,
          nickName: member.nickName
        }));
      } else {
        // 如果没有项目成员，显示所有用户
        projectMemberList.value = userList.value;
      }
    }).catch(error => {
      console.error('获取项目成员失败:', error);
      // 出错时显示所有用户
      projectMemberList.value = userList.value;
    });
  }).catch(() => {
    // 如果API不存在，使用所有用户列表
    projectMemberList.value = userList.value;
  });
}

/** 项目选择变化处理 */
const handleProjectChange = (projectId) => {
  getProjectMemberList(projectId);
  // 清空负责人和报告人选择
  form.value.assigneeId = null;
  form.value.reporterId = null;
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    taskId: null,
    projectId: null,
    parentId: null,
    taskName: null,
    taskCode: null,
    description: null,
    taskType: "development",
    status: "todo",
    priority: "medium",
    progress: 0,
    startDate: null,
    endDate: null,
    actualStartDate: null,
    actualEndDate: null,
    estimatedHours: null,
    actualHours: null,
    assigneeId: null,
    reporterId: null,
    sortOrder: 0,
    remark: null
  };
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.taskId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  isView.value = false;
  open.value = true;
  title.value = "添加任务管理";
}

/** 查看按钮操作 */
const handleView = (row: any) => {
  reset();
  const taskId = row.taskId
  getTask(taskId).then(response => {
    form.value = response.data;
    isView.value = true;
    open.value = true;
    title.value = "查看任务管理";
  });
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();
  const taskId = row.taskId || ids.value
  getTask(taskId).then(response => {
    form.value = response.data;
    isView.value = false;
    open.value = true;
    title.value = "修改任务管理";
  });
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.taskId != null) {
        updateTask(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy?.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const taskIds = row.taskId || ids.value
  proxy?.$modal.confirm('是否确认删除任务管理编号为"' + taskIds + '"的数据项？').then(function() {
    return delTask(taskIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
</script>